package com.eqdd.yiqidian.widget;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by lv on 17-9-12.
 */

public class CheckCodeView extends LinearLayout {

    int num = 0;
    ViewSource viewSource;
    OnComplete onComplete;

    public void setOnComplete(OnComplete onComplete) {
        this.onComplete = onComplete;
    }

    public CheckCodeView(Context context) {
        super(context);
        setOrientation(HORIZONTAL);
    }

    public CheckCodeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
    }

    public CheckCodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
    }


    public interface ViewSource {
        WatchDeleteKeyEditText loadSource();
    }

    public void setViewSource(ViewSource viewSource) {
        this.viewSource = viewSource;
    }

    public void setNum(Activity activity, int num) {
        this.num = num;
        for (int i = 0; i < num; i++) {
            if (viewSource != null) {
                WatchDeleteKeyEditText childAt = viewSource.loadSource();
                LinearLayout.LayoutParams layoutParams = new LayoutParams(getLayoutParams());
                layoutParams.weight = 1;
                layoutParams.width = 0;
                childAt.setLayoutParams(layoutParams);
                addView(childAt);
                childAt.setOnFocusChangeListener((v, hasFocus) -> {
                    if (hasFocus) {
                        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

                        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(childAt, InputMethodManager.SHOW_FORCED);

                    }
                });
                if (i < num - 1) {
                    childAt.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            if (s.length() == 1) {
                                int nowPos = indexOfChild(childAt);
                                setEnable(nowPos + 1);
                                getChildAt(nowPos + 1).setFocusable(true);
                                getChildAt(nowPos + 1).requestFocus();
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {

                        }
                    });
                }
                if (i == num - 1) {
                    childAt.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            if (s.length() == 1) {
                                if (onComplete != null) {
                                    StringBuilder stringBuilder = new StringBuilder();
                                    for (int j = 0; j < num; j++) {
                                        stringBuilder.append(((TextView) getChildAt(j)).getText().toString());
                                    }
                                    onComplete.complete(stringBuilder.toString());
                                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.hideSoftInputFromWindow(childAt.getWindowToken(), 0); //强制隐藏键盘
                                }
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {

                        }
                    });
                }
                if (i > 0) {
                    childAt.setWatchDeleteEvent((view, keyCode, keyEvent) -> {
                        if (keyCode == KeyEvent.KEYCODE_DEL && keyEvent.getAction() == KeyEvent.ACTION_UP) {
                            if (childAt.getText().length() == 1) {
                                childAt.setText("");
                            }
                            int now = indexOfChild(childAt);
                            setEnable(now - 1);
                            EditText priView = (EditText) getChildAt(now - 1);
                            priView.setText("");
                            priView.setFocusable(true);
                            priView.requestFocus();
                            return true;
                        } else {
                            return false;
                        }
                    });
                }
            }
        }
        setEnable(0);
    }

    public void clear() {
        for (int i = 0; i < num; i++) {
            ((EditText) getChildAt(i)).setText("");
        }
        setEnable(0);
        getChildAt(0).requestFocus();
    }

    public interface OnComplete {
        void complete(String code);
    }

    private void setEnable(int pos) {
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).setEnabled(pos == i);
        }
    }
}
